import SwiftUI
import CoreLocation

// MARK: - 苹果地理编码测试视图

struct AppleGeocodingTestView: View {
    @State private var testResults: [String] = []
    @State private var isLoading = false
    @State private var currentTest = ""
    
    private let geocodingService = AppleGeocodingService.shared
    
    // 测试坐标
    private let testCoordinates = [
        ("北京王府井", CLLocationCoordinate2D(latitude: 39.9161, longitude: 116.4037)),
        ("上海外滩", CLLocationCoordinate2D(latitude: 31.2304, longitude: 121.4737)),
        ("广州塔", CLLocationCoordinate2D(latitude: 23.1066, longitude: 113.3245)),
        ("深圳世界之窗", CLLocationCoordinate2D(latitude: 22.5405, longitude: 113.9344)),
        ("杭州西湖", CLLocationCoordinate2D(latitude: 30.2741, longitude: 120.1551)),
        ("成都宽窄巷子", CLLocationCoordinate2D(latitude: 30.6586, longitude: 104.0657)),
        ("西安兵马俑", CLLocationCoordinate2D(latitude: 34.3844, longitude: 109.2787)),
        ("南京夫子庙", CLLocationCoordinate2D(latitude: 32.0184, longitude: 118.7887))
    ]
    
    var body: some View {
        NavigationView {
            VStack(spacing: 20) {
                // 标题
                Text("AppleGeocodingService 测试")
                    .font(.largeTitle)
                    .fontWeight(.bold)
                    .padding(.top)
                
                Divider()
                
                // 当前测试状态
                if isLoading {
                    VStack {
                        ProgressView()
                            .scaleEffect(1.2)
                        Text("正在测试: \(currentTest)")
                            .font(.headline)
                            .foregroundColor(.blue)
                    }
                    .padding()
                }
                
                // 测试按钮
                VStack(spacing: 15) {
                    Button("开始完整测试") {
                        runFullTest()
                    }
                    .frame(maxWidth: .infinity)
                    .padding()
                    .background(Color.blue)
                    .foregroundColor(.white)
                    .cornerRadius(10)
                    .disabled(isLoading)
                    
                    Button("测试单个坐标") {
                        testSingleCoordinate()
                    }
                    .frame(maxWidth: .infinity)
                    .padding()
                    .background(Color.green)
                    .foregroundColor(.white)
                    .cornerRadius(10)
                    .disabled(isLoading)
                    
                    Button("清除结果") {
                        testResults.removeAll()
                    }
                    .frame(maxWidth: .infinity)
                    .padding()
                    .background(Color.orange)
                    .foregroundColor(.white)
                    .cornerRadius(10)
                }
                
                // 测试结果显示
                VStack(alignment: .leading, spacing: 10) {
                    Text("测试结果:")
                        .font(.headline)
                    
                    ScrollView {
                        LazyVStack(alignment: .leading, spacing: 8) {
                            ForEach(testResults, id: \.self) { result in
                                Text(result)
                                    .font(.system(.body, design: .monospaced))
                                    .padding(.horizontal, 8)
                                    .padding(.vertical, 4)
                                    .background(Color.gray.opacity(0.1))
                                    .cornerRadius(4)
                            }
                        }
                    }
                    .frame(maxHeight: 400)
                }
                
                Spacer()
            }
            .padding()
            .navigationTitle("地理编码测试")
            .navigationBarTitleDisplayMode(.inline)
        }
    }
    
    // MARK: - 测试方法
    
    private func runFullTest() {
        isLoading = true
        testResults.removeAll()
        
        addResult("🚀 开始AppleGeocodingService完整测试")
        addResult("📅 测试时间: \(Date())")
        addResult("📍 测试坐标数量: \(testCoordinates.count)")
        addResult("")
        
        Task {
            for (index, (name, coordinate)) in testCoordinates.enumerated() {
                await MainActor.run {
                    currentTest = "\(index + 1)/\(testCoordinates.count) - \(name)"
                }
                
                addResult("🔍 测试 \(index + 1): \(name)")
                addResult("   坐标: [\(coordinate.latitude), \(coordinate.longitude)]")
                
                let startTime = Date()
                
                if let addressInfo = await geocodingService.fetchAddressInfoAsync(
                    latitude: coordinate.latitude,
                    longitude: coordinate.longitude
                ) {
                    let duration = Date().timeIntervalSince(startTime)
                    
                    addResult("   ✅ 成功获取地址信息")
                    addResult("   📍 名称: \(addressInfo.name ?? "无")")
                    addResult("   🛣️ 街道: \(addressInfo.thoroughfare ?? "无")")
                    addResult("   🏙️ 城市: \(addressInfo.cityName)")
                    addResult("   🗺️ 省份: \(addressInfo.administrativeArea ?? "无")")
                    addResult("   🇨🇳 国家: \(addressInfo.countryName)")
                    addResult("   📋 完整地址: \(addressInfo.formattedAddress)")
                    addResult("   ⏱️ 耗时: \(String(format: "%.2f", duration))秒")
                } else {
                    let duration = Date().timeIntervalSince(startTime)
                    addResult("   ❌ 获取地址信息失败")
                    addResult("   ⏱️ 耗时: \(String(format: "%.2f", duration))秒")
                }
                
                addResult("")
                
                // 添加延迟避免API限制
                try? await Task.sleep(nanoseconds: 500_000_000) // 0.5秒
            }
            
            await MainActor.run {
                isLoading = false
                currentTest = ""
                addResult("🎉 测试完成！")
                addResult("📊 总计测试: \(testCoordinates.count) 个坐标")
            }
        }
    }
    
    private func testSingleCoordinate() {
        isLoading = true
        testResults.removeAll()
        
        addResult("🧪 开始单个坐标测试")
        addResult("📅 测试时间: \(Date())")
        addResult("")
        
        let testCoordinate = CLLocationCoordinate2D(latitude: 39.9161, longitude: 116.4037)
        
        Task {
            await MainActor.run {
                currentTest = "北京王府井"
            }
            
            addResult("🔍 测试坐标: 北京王府井")
            addResult("   坐标: [\(testCoordinate.latitude), \(testCoordinate.longitude)]")
            
            let startTime = Date()
            
            if let addressInfo = await geocodingService.fetchAddressInfoAsync(
                latitude: testCoordinate.latitude,
                longitude: testCoordinate.longitude
            ) {
                let duration = Date().timeIntervalSince(startTime)
                
                addResult("   ✅ 成功获取地址信息")
                addResult("   📍 名称: \(addressInfo.name ?? "无")")
                addResult("   🛣️ 街道: \(addressInfo.thoroughfare ?? "无")")
                addResult("   🏙️ 城市: \(addressInfo.cityName)")
                addResult("   🗺️ 省份: \(addressInfo.administrativeArea ?? "无")")
                addResult("   🇨🇳 国家: \(addressInfo.countryName)")
                addResult("   📋 完整地址: \(addressInfo.formattedAddress)")
                addResult("   ⏱️ 耗时: \(String(format: "%.2f", duration))秒")
            } else {
                let duration = Date().timeIntervalSince(startTime)
                addResult("   ❌ 获取地址信息失败")
                addResult("   ⏱️ 耗时: \(String(format: "%.2f", duration))秒")
            }
            
            await MainActor.run {
                isLoading = false
                currentTest = ""
                addResult("")
                addResult("🎉 单个测试完成！")
            }
        }
    }
    
    private func addResult(_ text: String) {
        DispatchQueue.main.async {
            testResults.append(text)
        }
    }
}

// MARK: - 预览

struct AppleGeocodingTestView_Previews: PreviewProvider {
    static var previews: some View {
        AppleGeocodingTestView()
    }
} 